@namespace BulmaRazor.Components
@inherits InputBase<TValue>
@inject BulmaRazorJsInterop JsInterop
@typeparam TValue

<input id="@Id" @attributes="Attributes" @bind="ShowValue"
       class="@classes"/>

@code {
    private IJSObjectReference _obj;

    [Parameter]
    public DatePickerOptions Options { get; set; }

    private string ShowValue
    {
        get { return ExtendMethods.GetShowValue(Value, Options.Format); }
        set
        {
            if (value.SetRealValue(out TValue val))
            {
                Value = val;
                ValueChanged.InvokeAsync(Value).GetAwaiter().GetResult();
            }
        }
    }


    [Parameter]
    public EventCallback OnShow { get; set; }

    [Parameter]
    public EventCallback OnHide { get; set; }

    [Parameter]
    public EventCallback OnChangeDate { get; set; }


    public override async Task SetParametersAsync(ParameterView parameters)
    {
        await base.SetParametersAsync(parameters);
        Options ??= new DatePickerOptions();
    }

    protected override void OnInitialized()
    {
        JSCallbackManager.AddEventHandler(Id, "show", new Func<Task>(() => OnShow.InvokeAsync()));
        JSCallbackManager.AddEventHandler(Id, "hide", new Func<Task>(() => OnHide.InvokeAsync()));
        JSCallbackManager.AddEventHandler(Id, "changeDate", new Func<Dictionary<string, object>, Task>((dict) =>
        {
            var value = dict["date"].ToString();
            ShowValue = value;
            return OnChangeDate.InvokeAsync();
        }));
        base.OnInitialized();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            _obj = await JsInterop.DatePickerInit(Id, Options);
        }
    }

    protected override async ValueTask DisposeAsync(bool disposing)
    {
        JSCallbackManager.DisposeObject(Id);
        if (_obj != null)
        {
            await _obj.DisposeAsync();
        }
    }

    public ValueTask Show()
    {
        return JsInterop.DatePickerShow(Id);
    }

    public ValueTask Hide()
    {
        return JsInterop.DatePickerHide(Id);
    }
}